package com.demo2do.boyle.backend.web.controller.customer;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.boyle.backend.service.customer.CustomerService;
import com.demo2do.boyle.backend.service.customer.WalletService;
import com.demo2do.boyle.backend.service.system.VariableService;
import com.demo2do.boyle.common.entity.AuditStatus;
import com.demo2do.boyle.common.entity.customer.Customer;
import com.demo2do.boyle.common.entity.customer.Source;
import com.demo2do.boyle.common.entity.customer.wallet.WalletRecord;
import com.demo2do.boyle.common.entity.system.Variable;
import com.demo2do.core.entity.Result;
import com.demo2do.core.persistence.support.Filter;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Page;

/**
 * 
 * @author mohanlan, Wilson, leo
 */
@Controller
@RequestMapping("/customers")
@MenuSetting("menu-customer")
public class CustomerController {

	private static final Logger logger = LoggerFactory.getLogger(CustomerController.class);
	
	/** mapping table: variable	id **/
	private static final Integer PROPERTY_TYPE = 1;
	
    @Autowired
    private CustomerService customerService;
    
    @Autowired
    private WalletService walletService;
    
    @Autowired
    private VariableService variableService;
    /**
     * list all customers
     * 
     * @return
     */
    @RequestMapping("")
    @MenuSetting("submenu-customer-list")
    public ModelAndView list(Page page) {

        ModelAndView modelAndView = new ModelAndView("customer/customer-list");
        
        int count = customerService.count(Customer.class);
        modelAndView.addObject("count", count);
        
        if(count > 0) {
        	List<Customer> customers = customerService.listByPage(Customer.class, page);
            modelAndView.addObject("customers", customers);
        }
        
        return modelAndView;
    }
    
    /**
     * display search panel
     * 
     * @return
     */
    @RequestMapping("/search")
    public String search() {
        return "customer/customer-search";
    }
    
    /**
     * do search
     * 
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-customer-list")
    public ModelAndView onSearch(Page page, HttpServletRequest request,
            @RequestParam(value = "nickName", required = false) String nickName,
            @RequestParam(value = "mobile", required = false) String mobile,
            @RequestParam(value = "source", required = false) Source source,
            @RequestParam(value = "auditStatus", required = false) AuditStatus auditStatus,
            @RequestParam(value = "createTimeBegin", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date createTimeBegin,
            @RequestParam(value = "createTimeEnd", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date createTimeEnd) {

        ModelAndView modelAndView = new ModelAndView("customer/customer-list");

        Filter filter = new Filter().addEquals("disabled", false)
                                    .addLike("profile.nickName", nickName)
                                    .addLike("mobile", mobile)
                                    .addEquals("source", source)
                                    .addEquals("auditStatus", auditStatus)
                                    .addDateTimeBetween("createTime", createTimeBegin, createTimeEnd);

        int count = customerService.count(Customer.class, filter);
        modelAndView.addObject("count", count);
        
        if(count > 0) {
        	List<Customer> customers = customerService.list(Customer.class, filter, page);
            modelAndView.addObject("customers", customers);
        }
        
        // handle query string
        String queryString = request.getQueryString();
        Map<String, String> queries = StringUtils.parseQueryString(queryString);
        if(queries.containsKey("page")) {
            queries.remove("page");
        }

        modelAndView.addObject("queryString", StringUtils.toQueryString(queries));
        
        return modelAndView;
    }
    
    /**
     * view customer detail
     * 
     * @return
     */
    @RequestMapping("/{id}")
    @MenuSetting("submenu-customer-list")
    public ModelAndView view(@PathVariable("id") Integer id, Page page) {

        ModelAndView modelAndView = new ModelAndView("customer/customer-view");

        Customer customer = customerService.load(Customer.class, id);
        List<WalletRecord> walletRecords = walletService.listRecords(customer.getWallet(), page);
        Variable variable = variableService.queryObjectForId(PROPERTY_TYPE);
        
        modelAndView.addObject("customer", customer);
        modelAndView.addObject("walletRecords", walletRecords);
        modelAndView.addObject("variable", variable);
        return modelAndView;
    }
    
    /**
     * prepare to create customer
     * 
     * @return
     */
    @RequestMapping("/create")
    public String create() {
        return "customer/customer-create";
    }

    /**
     * do create customer
     * 
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public String onCreate(Customer customer,
    					   @RequestParam("lifeTagCodes") List<Integer> lifeTagCodes, 
    					   @RequestParam("interestTagCodes") List<Integer> interestTagCodes) {

        Result result = new Result();

        try {
        	
        	customerService.create(customer, lifeTagCodes, interestTagCodes);
        	
            result.success().message("创建成功");

        } catch(Exception e) {
            result.fail().message("服务器异常");
            logger.info("onCreate()", e);
        }

        return JsonUtils.toJsonString(result);
    }

}
